import { Injectable } from '@angular/core';
import { LoginForm, LoginFormResponse, RegisterForm } from '../models/form';
import { HttpService } from './http.service';
import { AsyncData } from '../models/async-data';
import { User } from '../models/user';
import { authToken } from '../functions/utils';
import { Router } from '@angular/router';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  isLoggedIn = false;
  user: User;
  constructor(private http: HttpService, private router: Router) {}
  checkLogin(): Observable<boolean> {
    const item = this.getItem();
    if (this.isLoggedIn) {
      return of(true);
    }
    if (item === '') {
      this.router.navigate(['/home/login']);
      return of(false);
    }
    return this.http.get<User>('/users/getUserWithToken/' + item).pipe(
      map(data => {
        if (data.code === 1) {
          this.user = data.data;
          this.isLoggedIn = true;
          return true;
        }
        return false;
      })
    );
  }
  login({ account, password, remember }: LoginForm): void {
    this.http
      .post<LoginFormResponse>('/users/login', { account, password })
      .subscribe(({ code, data, msg }: AsyncData<LoginFormResponse>) => {
        if (code === 1) {
          this.isLoggedIn = true;
          this.user = data.user;
          if (remember) {
            this.setItem(data.token);
          }
          alert('登录成功');
          setTimeout(() => {
            this.router.navigate(['/user']);
          }, 1000);
        } else if (code === -1) {
          alert(msg);
        }
      });
  }
  register(form: RegisterForm) {
    this.http
      .post<LoginFormResponse>('/users', form)
      .subscribe(({ code, data, msg }: AsyncData<LoginFormResponse>) => {
        if (code === 1) {
          alert('注册成功');
          setTimeout(() => {
            this.router.navigate(['/home/login']);
          }, 1000);
        } else if (code === -1) {
          alert(msg);
        }
      });
  }
  logout(): void {
    this.isLoggedIn = false;
    this.removeItem();
    this.router.navigate(['/home/login']);
  }
  delTable(id: string, index) {
    this.http
      .delete('/luckytables/' + id)
      .subscribe(({ code, msg }: AsyncData<any>) => {
        if (code === 0) {
          alert('删除成功');
          this.user.tableInfoList.splice(index, 1);
        } else {
          alert(msg);
        }
      });
  }
  getItem(): string {
    const localToken = localStorage.getItem(authToken);
    return localToken !== null ? localToken : '';
  }
  setItem(newToken) {
    localStorage.setItem(authToken, newToken);
  }
  removeItem() {
    localStorage.removeItem(authToken);
  }
}
